// packageA/pages/package/kanban/kanban.js
import * as echarts from "../../../components/echarts/echarts";
const mybehavior = require("../../../../behaviors/requests")

var company = wx.getStorageSync('company')
var chart;
var chart1;
function getDate() {
  // 获取当前日期
  let today = new Date();

  // 获取当前月份
  let currentMonth = today.getMonth();

  // 获取当前年份
  let currentYear = today.getFullYear();

  // 获取当前月份的第一天
  let firstDay = new Date(currentYear, currentMonth, 1);


  // 获取当前月份的最后一天
  // 下个月的第一天减去一天就是当前月的最后一天
  let lastDay = new Date(currentYear, currentMonth + 1, 0);

  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1，并确保为两位数
    const day = String(date.getDate()).padStart(2, '0'); // 确保日期为两位数
    return `${year}-${month}-${day}`;
  };
  return {
    firstDay: formatDate(firstDay),
    lastDay: formatDate(lastDay)
  };
}
function drawChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);
  const days = getDate();
  let url = "https://logisticsengineering.gree.com/scene_api/fiveS_manage/c_distribute"
  let data = {
    start_time_str: days.firstDay,
    end_time_str: days.lastDay,
    company: company

  }
  var token = wx.getStorageSync('token')
  wx.request({
    url: url,
    method: "post",
    data: data,
    header: {
      "Authorization": token
    },
    success(res) {
      let result = res.data.data
      const lists = Object.entries(result).map(([name, value]) => ({ name, value }));
      var option = {

        toolbox: {
          show: true,

        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },


        legend: {
          top: '0',
          left: 'center',

        },
        series: [
          {

            name: 'Access From',
            type: 'pie',
            radius: ['15%', '45%'],
            center: ['50%', "60%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 30,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: lists,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  formatter: ' {c} ({d}%)'
                },
                labelLine: { show: true }
              }
            }


          }
        ]
      };

      chart.setOption(option);
    }
  });



}
function drawChart1(canvas, width, height, dpr) {
  chart1 = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart1);
  const days = getDate();
  let url = "https://logisticsengineering.gree.com/scene_api/fiveS_manage/manager_distribute"
  let data = {
    start_time_str: days.firstDay,
    end_time_str: days.lastDay,
    company: company

  }
  var token = wx.getStorageSync('token')
  wx.request({
    url: url,
    method: "post",
    data: data,
    header: {
      "Authorization": token
    },
    success(res) {
      let result = res.data.data
      let bottom_list = []
      let series_list = []
      const lists = Object.entries(result).map(([name, value]) => ({ name, value }));

      for (let i in lists) {
        bottom_list.push(lists[i].name)
        if (i % 2 == 0) {
          let obj = {
            value: lists[i].value,
            itemStyle: {
              color: '#5555FF'
            }
          }
          series_list.push(obj)
        } else {
          let obj = {
            value: lists[i].value,
            itemStyle: {
              color: '#AAFFF3'
            }
          }
          series_list.push(obj)
        }


      }

      var option1 = {
        xAxis: {
          type: 'category',
          axisLabel: { interval: 0, rotate: 30 },
          data: bottom_list
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: series_list,
            type: 'bar',
            label: {
              show: true, // 显示数值
              position: 'top' // 数值显示的位置
            }
          }
        ]
      };
      chart1.setOption(option1);
    }
  });

}


Page({


  /**
   * 页面的初始数据
   */
  behaviors: [mybehavior],
  data: {
    baseUrl: "https://logisticsengineering.gree.com/scene_api/fiveS_manage",
    test_chart1: null,
    ec: {
      onInit: drawChart,

    },
    ec1: {
      onInit: drawChart1
    },

    time_gt: "",
    time_lt: "",
    company: "",
    user_num: 0,
    option_data: [],
    month: 0,
    problem_category: '',
    options1: ["珠海格力电器股份有限公司","格力电器（成都）有限公司"],
    options2: ["珠海格力电器股份有限公司","格力电器（成都）有限公司"],
    isHidden: false,
    isHidden2: false,
    total: 0,
    not_total: 0,
    done_total: 0,
    month_list: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12',],
    picker_disabled: true,
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    minDate: new Date(),
    show: false
  },
  dateShow() {
    this.setData({
      isHidden: true,
      show: true

    })
  },
  onDateClose() {
    this.setData({
      isHidden: false,
      show: false

    })
  },
  onDateConfirm(e) {
    this.setData({
      show: false,
    })
    wx.showLoading({
      title: '加载中...',
    })
    const givenDateStr = this.formatDate1(new Date(e.detail))
    let daysStr = this.getFirstAndLastDayOfMonthAsString(givenDateStr);
    console.log('第一天:', daysStr.firstDayStr); // 输出: 第一天: 2025-01-01
    console.log('最后一天:', daysStr.lastDayStr);

    this.setData({
      month: givenDateStr.slice(0, 7),
      time_gt: daysStr.firstDayStr,
      time_lt: daysStr.lastDayStr,
    })
    this.getBaseDatas()
    this.getCategoryChangeDatas()
    this.getDepartmentChangeDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
        show: false
      })
      wx.hideLoading()
    }, 1000)

  },

  // 获取--公司名称--数据
  getCompanyDatas() {
    let url = "https://logisticsengineering.gree.com/scene_api/data_auth_manage/get_u_permission"
    let data = {

    }
    this.post(url, data).then(res => {
      // console.log("公司名称", res.data)
      let data_list = Object.keys(res.data)

      if (res.code == 20000) {

        this.setData({
          options1: data_list,

        })

      } else {
        // wx.showToast({
        //   title: res.msg,
        //   icon: 'error'
        // })
      }
    }).catch(err => {
      console.log(err);
      // wx.showToast({
      //   title: err.msg,
      //   icon: 'error'
      // })
    })
  },
  // 获取--月度问题概况数据--数据
  getBaseDatas() {
    let url = this.data.baseUrl + "/result_distribute"
    let data = {
      company: this.data.company,
      start_time_str: this.data.time_gt,
      end_time_str: this.data.time_lt,
    }
    this.post(url, data).then(res => {

      if (res.code == 20000) {
        const not_total = res.data.unknown == undefined ? 0 : res.data.unknown
        const done_total = res.data.yes == undefined ? 0 : res.data.yes
        this.setData({
          not_total: not_total,
          done_total: done_total,
          total: not_total + done_total,

        })

      } else {
        this.setData({
          total: 0,
          not_total: 0,
          done_total: 0,

        })
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      this.setData({
        total: 0,
        not_total: 0,
        done_total: 0,

      })
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  getPickerVlaueClose() {
    wx.showLoading({
      title: '加载中...',
    })
    this.getBaseDatas()

    setTimeout(() => {
      this.setData({
        isHidden: false,

      })
      wx.hideLoading()
    }, 1000)
  },
  getPickerVlaueClose1() {
    wx.showLoading({
      title: '加载中...',
    })
    this.getBaseDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
      })
      wx.hideLoading()
    }, 1000)

  },

  ecShow() {
    this.setData({
      isHidden: true,
    })
  },
  ecShow2() {
    this.setData({
      isHidden: true,
      isHidden2: true,

    })
  },
  // 更换公司
  getPickerVlaue(e) {
    wx.showLoading({
      title: '加载中...',
    })
    console.log(e.detail);
    this.setData({
      company: e.detail,
    })
    this.getBaseDatas()
    this.getCategoryChangeDatas()
    this.getDepartmentChangeDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
      })
      wx.hideLoading()
    }, 1000)
  },
  // 更换月份
  getPickerVlaue1(e) {
    wx.showLoading({
      title: '加载中...',
    })
    const select_data = this.getFirstAndLastDayOfMonthAsString(e.detail)
    this.setData({
      month: select_data.split(6),
      time_gt: select_data.firstDay,
      time_lt: select_data.lastDay,
    })
    this.getBaseDatas()
    this.getCategoryChangeDatas()
    this.getDepartmentChangeDatas()
    setTimeout(() => {
      this.setData({
        isHidden: false,
      })
      wx.hideLoading()
    }, 1000)
  },
  getFirstAndLastDayOfMonthAsString(dateStr) {
    let date = new Date(dateStr);

    // 获取当前月份（0-11）和年份
    let month = date.getMonth();
    let year = date.getFullYear();

    // 第一天：当前月份的第一天，日期设为1
    let firstDay = new Date(year, month, 1);

    // 最后一天：下个月的第一天减一
    let lastDay = new Date(year, month + 1, 0);

    // 辅助函数：将Date对象格式化为yyyy-MM-dd字符串
    function formatDate(d) {
      let monthStr = (d.getMonth() + 1).toString().padStart(2, '0');
      let dayStr = d.getDate().toString().padStart(2, '0');
      return `${d.getFullYear()}-${monthStr}-${dayStr}`;
    }

    // 格式化第一天和最后一天的日期
    let firstDayStr = formatDate(firstDay);
    let lastDayStr = formatDate(lastDay);

    // 返回结果对象
    return {
      firstDayStr: firstDayStr,
      lastDayStr: lastDayStr
    };
  },




  // 获取--月份更换问题类别--数据
  getCategoryChangeDatas() {
    let url = this.data.baseUrl + "/c_distribute"
    let data = {
      start_time_str: this.data.time_gt,
      end_time_str: this.data.time_lt,
      company: this.data.company

    }
    this.post(url, data).then(res => {
      console.log("月份更换问题类别", res.data)

      if (res.code == 20000) {
        let result = res.data
        const lists = Object.entries(result).map(([name, value]) => ({ name, value }));

        var option = {

          toolbox: {
            show: true,

          },
          tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
          },


          legend: {
            top: '0',
            left: 'center',

          },
          series: [
            {

              name: 'Access From',
              type: 'pie',
              radius: ['15%', '45%'],
              center: ['50%', "60%"],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 30,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: lists,
              itemStyle: {
                normal: {
                  label: {
                    show: true,
                    formatter: ' {c} ({d}%)'
                  },
                  labelLine: { show: true }
                }
              }


            }
          ]
        };

        chart.setOption(option);

      } else {
        chart.setOption({});

      }
    }).catch(err => {
      var option = {

        toolbox: {
          show: true,

        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },


        legend: {
          top: '0',
          left: 'center',

        },
        series: [
          {

            name: 'Access From',
            type: 'pie',
            radius: ['15%', '45%'],
            center: ['50%', "60%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 30,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [],
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  formatter: ' {c} ({d}%)'
                },
                labelLine: { show: true }
              }
            }


          }
        ]
      };
      chart.setOption(option);
      console.log(err);
      // wx.showToast({
      //   title: err.msg,
      //   icon: 'error'
      // })
    })
  },
  // 获取--月份更换各单位问题数量--数据
  getDepartmentChangeDatas() {
    let url = this.data.baseUrl + "/manager_distribute"
    let data = {
      start_time_str: this.data.time_gt,
      end_time_str: this.data.time_lt,
      company: this.data.company

    }
    this.post(url, data).then(res => {
      console.log("月份更换问题类别", res.data)

      if (res.code == 20000) {
        let result = res.data
        let bottom_list = []
        let series_list = []
        const lists = Object.entries(result).map(([name, value]) => ({ name, value }));

        for (let i in lists) {
          bottom_list.push(lists[i].name)
          if (i % 2 == 0) {
            let obj = {
              value: lists[i].value,
              itemStyle: {
                color: '#5555FF'
              }
            }
            series_list.push(obj)
          } else {
            let obj = {
              value: lists[i].value,
              itemStyle: {
                color: '#AAFFF3'
              }
            }
            series_list.push(obj)
          }


        }

        var option1 = {
          xAxis: {
            type: 'category',
            axisLabel: { interval: 0, rotate: 30 },
            data: bottom_list
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: series_list,
              type: 'bar',
              label: {
                show: true, // 显示数值
                position: 'top' // 数值显示的位置
              }
            }
          ]
        };
        chart1.setOption(option1);

      } else {
        chart.setOption({});

      }
    }).catch(err => {
      var option1 = {
        xAxis: {
          type: 'category',
          axisLabel: { interval: 0, rotate: 30 },
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [],
            type: 'bar',
            label: {
              show: true, // 显示数值
              position: 'top' // 数值显示的位置
            }
          }
        ]
      };
      chart1.setOption(option1);
      console.log(err);
      // wx.showToast({
      //   title: err.msg,
      //   icon: 'error'
      // })
    })
  },

  getLastMonthDates() {
    // 获取当前日期
    let today = new Date();

    // 获取当前月份
    let currentMonth = today.getMonth();

    // 获取当前年份
    let currentYear = today.getFullYear();

    // 获取当前月份的第一天
    let firstDay = new Date(currentYear, currentMonth, 1);


    // 获取当前月份的最后一天
    // 下个月的第一天减去一天就是当前月的最后一天
    let lastDay = new Date(currentYear, currentMonth + 1, 0);

    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1，并确保为两位数
      const day = String(date.getDate()).padStart(2, '0'); // 确保日期为两位数
      return `${year}-${month}-${day}`;
    };


    this.setData({
      time_gt: formatDate(firstDay),
      time_lt: formatDate(lastDay),
      month: formatDate(lastDay).slice(0, 7),
    })
    this.getBaseDatas()
    console.log(firstDay);
    console.log(lastDay);

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let com = wx.getStorageSync('company')
    if (com == '珠海格力电器股份有限公司') {
      this.setData({
        picker_disabled: false
      })
    }
    company = com
    this.setData({
      company: com,
    })
    // this.getCompanyDatas()
    this.getLastMonthDates()
    // this.getAllProblemDatas()
    // // this.getProblemNumDatas()
    // // this.getNumAndCategoryDatas()
    // this.getRegisteredDatas()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {


  },

  /**
   * 生命周期函数--监听页面隐藏0.000000000000000000000000000000
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})